#include <iostream>
#include <unistd.h>
#include <pthread.h>

using namespace std;
const int n = 100;
int ticket = 10000;
class ThraedData{
public:
    ThraedData(string name,pthread_mutex_t& mtx)
    :_name(name),_mtx(mtx)
    {}
    ~ThraedData()
    {}
public:
    string _name;
    pthread_mutex_t& _mtx;
};

void* threadRun(void* arg){
    ThraedData* td = static_cast<ThraedData*>(arg);
    int sum = 0;
    while(true){
        pthread_mutex_lock(&td->_mtx);
        if(ticket>0){
            //usleep(1000);
            ticket--;
            //cout<<"线程："<<td->_name<<"抢票成功"<<"剩余："<<ticket<<"张票"<<endl;
            sum++;
            pthread_mutex_unlock(&td->_mtx);
        }else{
            pthread_mutex_unlock(&td->_mtx);
            break;
        }
        usleep(1000);
    }
    pthread_mutex_lock(&td->_mtx);
    cout<<"线程："<<td->_name<<"抢票数量："<<sum<<endl;
    pthread_mutex_unlock(&td->_mtx);
    delete td;
    return nullptr;
}


int main()
{
    pthread_t pts[n];
    pthread_mutex_t mtx;
    pthread_mutex_init(&mtx,nullptr);
    for(int i = 0;i<n;++i){
        char* name = new char[64];
        snprintf(name,64,"Thread-%d",i);
        ThraedData* td = new ThraedData(name,mtx);
        pthread_create(pts+i,nullptr,threadRun,td);
    }

    for(int i = 0;i<n;++i){
        int ret = pthread_join(pts[i],nullptr);
        if(ret!=0){
            perror("线程回收失败");
            return 1;
        }
    }
    cout<<"所有线程回收完毕,剩余票数为："<<ticket<<endl;
    pthread_mutex_destroy(&mtx);
    return 0;
}